<template>
  <div>
    <page-main>
      <el-row :gutter="20">
        <el-col :span="4">
          <div class="flexRow">
            <span style="width: 120px">人数限制</span>
            <el-input-number :min="0" v-model="searchForm.limit_person"></el-input-number>
          </div>
        </el-col>
        <el-col :span="5">
          <div class="flexRow">
            <span style="width: 150px">演练开始时间</span>
            <el-date-picker
              v-model="searchForm.start_time"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </div>
        </el-col>
        <el-col :span="5">
          <div class="flexRow">
            <span style="width: 150px">演练结束时间</span>
            <el-date-picker v-model="searchForm.end_time" type="date" placeholder="选择日期" value-format="YYYY-MM-DD">
            </el-date-picker>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="flexRow">
            <el-button type="primary" @click="searchBtn">搜索</el-button>
            <el-button type="warning" @click="refreshBtn">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </page-main>
    <page-main>
      <div style="margin: 10px 0">
        <span style="margin-right: 10px; font-weight: bold">演练总次数{{ statisticsData.total }}</span>
        <span style="font-weight: bold">演练完成次数{{ statisticsData.reportTotal }}</span>
      </div>
      <el-table :data="dataList" :default-sort="{ prop: 'id', order: 'ascending' }" v-loading="dataListLoading">
        <el-table-column label="演练名称" prop="activity_name"></el-table-column>
        <el-table-column label="演练地点" prop="address"></el-table-column>
        <el-table-column label="区域" prop="region_name"></el-table-column>
        <el-table-column label="所属单位" prop="unit_name"></el-table-column>
        <el-table-column label="限制人数" prop="limit_person"></el-table-column>
        <el-table-column label="报名开始时间" prop="sign_time_begin">
          <template #default="scope">
            <div>{{ formatDate(scope.row.sign_time_begin * 1000) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="报名结束时间" prop="sign_time_end">
          <template #default="scope">
            <div>{{ formatDate(scope.row.sign_time_end * 1000) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="演练开始时间" prop="time_begin">
          <template #default="scope">
            <div>{{ formatDate(scope.row.time_begin * 1000) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="演练结束时间" prop="time_end">
          <template #default="scope">
            <div>{{ formatDate(scope.row.time_end * 1000) }}</div>
          </template>
        </el-table-column>
        <el-table-column width="130">
          <template #default="scope">
            <el-button type="primary" size="mini" @click="editPerson(scope.row.id)">查看已报名人列表</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column>
                  <template #default="scope">
                      <el-button type="primary" size="mini" @click="details(scope.row.id)">查看详情</el-button>
                  </template>
              </el-table-column> -->
        <el-table-column width="150">
          <template #header>
            <el-button size="mini" type="primary" @click="addEdit('add')">添加</el-button>
          </template>
          <template #default="scope">
            <div>
              <el-button size="mini" @click="addEdit(scope.$index, scope.row)">修改</el-button>
              <!-- <el-button type="danger" size="mini" @click="del(scope.row)">删除</el-button> -->
              <el-popconfirm
                confirm-button-text="删除"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除？"
                @confirm="del(scope.row)"
              >
                <template #reference>
                  <el-button size="mini" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div style="margin-top: 4px">
              <el-button size="mini" type="success" @click="showWriteResultDialog(scope.row)">结果</el-button>
              <el-button size="mini" type="success" @click="addEdit(scope.$index, scope.row, 1)">详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          :current-page="pagination.page"
          :total="total"
          :page-size="pagination.size"
          :page-sizes="pagination.sizes"
          :layout="pagination.layout"
          class="pagination"
          background
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
        />
      </div>
    </page-main>
    <el-dialog
      :title="dialogTitle"
      v-model="dialogFormVisible"
      :close-on-click-modal="false"
      destroy-on-close
      @close="closeDialog"
      width="50%"
    >
      <el-form :model="formData" :rules="rules" ref="addForm">
        <el-row>
          <el-col :span="20" :offset="1">
            <el-form-item label="演练名称" prop="activity_name">
              <el-input v-model="formData.activity_name" :disabled="is_show_detail"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="20" :offset="1">
            <el-form-item label="演练地点" prop="address">
              <el-input v-model="formData.address" :disabled="is_show_detail"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="限制人数" prop="limit_person">
              <el-input-number :min="1" v-model="formData.limit_person" :disabled="is_show_detail"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="20" :offset="1">
            <el-form-item label="报名时间" prop="sign_time_begin">
              <el-date-picker
                v-model="sign_time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
               
                @change="signChange"
                :disabledDate="disabledDate"
                :disabled="is_show_detail"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="20" :offset="1">
            <el-form-item label="演练时间" prop="time_begin">
              <el-date-picker
                v-model="activity_time"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"

                @change="activityChange"
                :disabledDate="disabledDate"
                :disabled="is_show_detail"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5" :offset="1">
            <el-form-item label="封面图" prop="cover">
              <el-upload
                :action="upDataUrl + '/unit/upload/upload'"
                :on-change="coverChange"
                :file-list="coverFileList"
                :headers="upLoadImgHeader"
                :data="upLoadImgData"
                limit="1"
                :on-success="coverFileUpSuccess"
                list-type="picture-card"
                class="cover"
                :before-remove="coverRemove"
                accept=".jpg,.png,.jpeg"
                :on-preview="handlePictureCardPreview"
                :disabled="is_show_detail"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="20" :offset="1">
            <el-form-item label="视频" prop="video">
              <div class="videoBox">
                <el-upload
                  v-if="!is_show_detail"
                  class="uploadVideo"
                  :action="upDataUrl + '/unit/upload/upload'"
                  :on-progress="uploadVideoProcess"
                  :on-success="handleVideoSuccess"
                  :before-upload="beforeUploadVideo"
                  :show-file-list="false"
                  :headers="upLoadImgHeader"
                  accept=".mp4,.ogg,.flv,.avi,.wmv,.rmvb,.mov"
                  :data="upLoadViedeoData"
                >
                  <el-button size="small" type="primary">{{ videoHint }}</el-button>
                </el-upload>
                <el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent" class="progress">
                </el-progress>
                <video
                  v-if="showVideoPath && showVideoPath.length"
                  :src="upDataUrl + showVideoPath"
                  class="avatar video-avatar"
                  controls="controls"
                >
                  您的浏览器不支持视频播放
                </video>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="20" :offset="1">
            <el-form-item label="警情设定" prop="rule">
              <div id="rule"></div>
            </el-form-item>
          </el-col>
          <el-col :span="20" :offset="1">
            <el-form-item label="演练详情" prop="activity_remark">
              <div id="activity_remark"></div>
            </el-form-item>
          </el-col>
          <el-col :offset="1">
            <el-form-item label="状态" prop="activity_name">
              <el-switch
                v-model="formData.status"
                active-text="关闭"
                inactive-text="正常"
                :active-value="2"
                :inactive-value="1"
                inactive-color="#13CE66"
                active-color="#FF4949"
                :disabled="is_show_detail"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">{{ is_show_detail ? '返回' : '取 消' }}</el-button>
          <el-button type="primary" @click="submitForm" v-if="!is_show_detail">确 定</el-button>
        </span>
      </template>
      <!-- 图片放大 -->
      <el-dialog v-model="dialogVisible">
        <img style="width: 100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </el-dialog>
    <el-dialog v-model="writeResultDialogVisible" width="60%" @close="activityResultClose">
      <div id="activityResult"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="writeResultDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitResult">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
// 分页
import paginationMixin from '@/mixins/pagination'
// 富文本
import E from 'wangeditor'
export default {
  // 分页
  mixins: [paginationMixin],
  data() {
    return {
      is_show_detail: false,
      searchForm: {
        limit_person: '',
        start_time: '',
        end_time: ''
      },
      // 活动详情富文本
      activityEditor: '',
      // 规则富文本
      ruleEditor: '',
      total: 0,
      //是否显示进度条
      videoFlag: false,
      //进度条的进度，
      videoUploadPercent: '',
      showVideoPath: '',
      videoHint: '选择视频',
      // 文件类型
      // accept: ".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.txt",
      upDataUrl: import.meta.env.DEV ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
      searchValue: '',
      // 报名时间
      sign_time: [],
      // 活动时间
      activity_time: [],
      // 总页数
      total: 0,
      // 表单
      formData: {
        id: 0,
        activity_name: '',
        activity_remark: '',
        video: '',
        cover: '',
        rule: '',
        annex: [],
        address: '',
        sign_time_begin: '',
        sign_time_end: '',
        time_begin: '',
        time_end: '',
        limit_person: '',
        create_time: '',
        update_time: '',
        status: 1
      },
      // 列表
      dataList: [],
      dataListLoading: false,
      dialogFormVisible: false,
      // 图片
      coverFileList: [],
      upLoadImgData: {
        type: 'image'
      },
      upLoadViedeoData: {
        type: 'video'
      },
      //   图片放大
      dialogImageUrl: '',
      dialogVisible: false,
      rules: {
        activity_name: [{ required: true, message: '请输入', trigger: 'blur' }],
        activity_remark: [{ required: true, message: '请输入', trigger: 'blur' }],
        // video: [{ required: true, message: "请选择", trigger: "blur" }],
        cover: [{ required: true, message: '请选择', trigger: 'blur' }],
        rule: [{ required: true, message: '请输入', trigger: 'blur' }],
        annex: [{ required: true, message: '请选择', trigger: 'blur' }],
        address: [{ required: true, message: '请输入', trigger: 'blur' }],
        time_begin: [{ required: true, message: '请选择', trigger: 'change' }],
        sign_time_begin: [{ required: true, message: '请选择', trigger: 'change' }],
        limit_person: [{ required: true, message: '请输入', trigger: 'blur' }],
        status: [{ required: true }]
      },
      writeResultDialogVisible: '',
      writeResultId: '',
      activityResult: '',
      writeResultDialogVisible: false,
      statisticsData: ''
    }
  },
  computed: {
    upLoadImgHeader() {
      return {
        'A-Token': this.$store.state.user.a_token,
        'U-Token': this.$store.state.user.u_token
      }
    }
  },
  watch: {
    is_show_detail: (newVal, oldVal) => {
      if (newVal) {
      }
    }
  },
  created() {
    this.getDataList()
    this.getStatisticsData()
  },
  mounted() {},
  methods: {
    getStatisticsData() {
      this.$api
        .post('/unit/Activity/Count', {
          activity_type: '灭火救援演练',
          start_time: this.searchForm.start_time,
          end_time: this.searchForm.end_time
        })
        .then((res) => {
          this.statisticsData = res.data
        })
    },
    activityResultClose() {
      this.activityResult.destroy()
      this.activityResult = ''
    },
    submitResult() {
      if (this.activityResult.txt.html()) {
        this.$api
          .post('/unit/Activity/Save', {
            id: this.writeResultId,
            report: this.activityResult.txt.html(),
            activity_type: '灭火救援演练'
          })
          .then((res) => {
            this.$message.success('保存成功')
            this.writeResultDialogVisible = false
            this.getDataList()
            this.getStatisticsData()
          })
      } else {
        this.$message.error('请填写')
      }
    },
    showWriteResultDialog(row) {
      this.writeResultId = row.id
      this.writeResultDialogVisible = true
      this.$nextTick(() => {
        let activityResult = new E('#activityResult')
        activityResult.config.excludeMenus = ['video']
        activityResult.config.customUploadImg = (resultFiles, insertImgFn) => {
          let file = resultFiles[0] //转化为易于理解的file对象
          let param = new FormData()
          param.append('file', file)
          param.append('type', 'image')
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundarynl6gT1BKdPWIejNq'
            }
          }
          this.$api.post('/unit/Upload/upload', param, config).then((res) => {
            insertImgFn(this.upDataUrl + res.data.result)
          })
        }
        this.activityResult = activityResult
        this.activityResult.create()
        this.activityResult.txt.html(row.report)
      })
    },
    disabledDate(date) {
      return date.getTime() < Date.now() - 24 * 60 * 60 * 1000
    },
    // 获取数据
    getDataList() {
      // 分页
      this.dataListLoading = true
      let query = {
        rows: this.pagination.size,
        page: this.pagination.page,
        ...this.searchForm,
        activity_type: '灭火救援演练'
      }

      if (query.limit_person == 0) query.limit_person = ''
      this.$api
        .post('/unit/Activity/Lists', query)
        .then((res) => {
          this.dataList = res.data.list
          this.total = res.data.total
        })
        .finally(() => {
          this.dataListLoading = false
        })
    },
    // 搜索
    searchBtn() {
      this.getDataList()
      this.getStatisticsData()
    },
    refreshBtn() {
      let temp = this.searchForm
      for (let key in temp) {
        temp[key] = ''
      }
      this.searchForm = temp
      this.getDataList()
      this.getStatisticsData()
    },
    // 添加修改
    addEdit(status, row, is_detail) {
      // 富文本
      this.is_show_detail = !!is_detail
      setTimeout(() => {
        let activityEditor = new E('#activity_remark')
        activityEditor.config.excludeMenus = ['video']
        activityEditor.config.customUploadImg = (resultFiles, insertImgFn) => {
          let file = resultFiles[0] //转化为易于理解的file对象
          let param = new FormData()
          param.append('file', file)
          param.append('type', 'image')
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundarynl6gT1BKdPWIejNq'
            }
          }
          this.$api.post('/unit/Upload/upload', param, config).then((res) => {
            insertImgFn(this.upDataUrl + res.data.result)
          })
        }
        this.activityEditor = activityEditor
        this.activityEditor.create()
        let ruleEditor = new E('#rule')
        ruleEditor.config.excludeMenus = ['video']
        ruleEditor.config.customUploadImg = (resultFiles, insertImgFn) => {
          let file = resultFiles[0] //转化为易于理解的file对象
          let param = new FormData()
          param.append('file', file)
          param.append('type', 'image')
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundarynl6gT1BKdPWIejNq'
            }
          }
          this.$api.post('/unit/Upload/upload', param, config).then((res) => {
            insertImgFn(this.upDataUrl + res.data.result)
          })
        }
        this.ruleEditor = ruleEditor
        this.ruleEditor.create()
      }, 100)
      this.dialogFormVisible = true
      if (status != 'add') {
        this.$api.post('/unit/Activity/Show', { id: row.id }).then((res) => {
          let data = res.data
          this.sign_time = [new Date(row.sign_time_begin * 1000), new Date(row.sign_time_end * 1000)]
          this.activity_time = [new Date(row.time_begin * 1000), new Date(row.time_end * 1000)]
          this.formData = data
          // 富文本
          this.activityEditor.txt.html(data.activity_remark)
          this.ruleEditor.txt.html(data.rule)
          // 判断是否有封面图
          if (data.cover) {
            this.coverFileList = [{ url: this.upDataUrl + row.cover }]
            let cover = document.getElementsByClassName('cover')[0]
            cover.children[1].style.display = 'none'
          }
          // 判断是否有视频
          if (data.video) {
            this.showVideoPath = data.video
            this.formData.video = data.video
            this.videoHint = '重新选择'
          }
        })
      }
    },
    // 取消
    cancel() {
      this.dialogFormVisible = false
      this.closeDialog()
    },
    // 点击删除
    del(row) {
      row.status = -1
      row.activity_type = '灭火救援演练'
      this.$api.post('/unit/Activity/Save', row).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getDataList()
          this.getStatisticsData()
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 查看详情
    details(id) {
      this.$router.push({
        name: 'activityDetails',
        query: {
          id
        }
      })
    },
    // 查看人数列表
    editPerson(id) {
      this.$router.push({
        name: 'activityPersons',
        query: {
          id
        }
      })
    },
    // 提交
    submitForm() {
      this.formData.activity_remark = this.activityEditor.txt.html()
      this.formData.rule = this.ruleEditor.txt.html()
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$api
            .post('/unit/Activity/Save', {
              ...this.formData,
              activity_type: '灭火救援演练'
            })
            .then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: res.msg
                })
                this.getDataList()
                this.getStatisticsData()
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
              this.dialogFormVisible = false
              this.closeDialog()
            })
        } else {
          ElMessage.error('请填写完整')
          return false
        }
      })
    },
    // 模态框关闭触发
    closeDialog() {
      this.activityEditor.txt.html('')
      this.ruleEditor.txt.html('')
      this.activity_time = []
      this.sign_time = []
      this.coverFileList = []
      this.formData = {
        id: 0,
        activity_name: '',
        activity_remark: '',
        video: '',
        cover: '',
        rule: '',
        annex: [],
        address: '',
        sign_time_begin: '',
        sign_time_end: '',
        time_begin: '',
        time_end: '',
        limit_person: '',
        create_time: '',
        update_time: ''
      }
      this.videoHint = '选择视频'
      this.showVideoPath = ''
      // 模态框隐藏后 销毁富文本
      this.activityEditor.destroy()
      this.ruleEditor.destroy()
      let cover = document.getElementsByClassName('cover')[0]
      cover.children[1].style.display = 'block'
    },
    // 选择报名时间执行
    signChange(date) {
      this.formData.sign_time_begin = date[0].getTime() / 1000
      this.formData.sign_time_end = date[1].getTime() / 1000
    },
    // 选择活动时间执行
    activityChange(date) {
      this.formData.time_begin = date[0].getTime() / 1000
      this.formData.time_end = date[1].getTime() / 1000
    },
    // 时间格式化
    formatDate(timeStamp, format) {
      if (!timeStamp) return ''
      timeStamp = +timeStamp
      var date = new Date(timeStamp)
      // 年月日
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      month = month < 10 ? '0' + month : month
      var day = date.getDate()
      day = day < 10 ? '0' + day : day
      // 时分秒
      var hour = date.getHours()
      hour = hour < 10 ? '0' + hour : hour
      var min = date.getMinutes()
      min = min < 10 ? '0' + min : min
      var sec = date.getSeconds()
      sec = sec < 10 ? '0' + sec : sec
      if (format) {
        format = format.replace('Y', year)
        format = format.replace('M', month)
        format = format.replace('D', day)
        format = format.replace('h', hour)
        format = format.replace('m', min)
        format = format.replace('s', sec)
        return format
      } else {
        return year + '-' + month + '-' + day
      }
    },
    // 选择图片
    coverChange() {
      let cover = document.getElementsByClassName('cover')[0]
      cover.children[1].style.display = 'none'
    },
    //   移除图片
    coverRemove() {
      let cover = document.getElementsByClassName('cover')[0]
      cover.children[1].style.display = 'block'
      this.formData.cover = ''
    },
    //   图片放大
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 图片上传成功
    coverFileUpSuccess(res) {
      this.formData.cover = res.data.result
    },
    //上传前回调
    beforeUploadVideo(file) {
      // var fileSize = file.size / 1024 / 1024 < 50;
      if (
        ['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(
          file.type
        ) == -1
      ) {
        this.$message({
          type: 'error',
          message: '请上传正确的视频格式'
        })
        return false
      }
      // if (!fileSize) {
      //     layer.msg("视频大小不能超过50MB");
      //     return false;
      // }
    },
    //进度条
    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = true
      this.videoUploadPercent = file.percentage.toFixed(0) * 1
    },
    //上传成功回调
    handleVideoSuccess(res, file) {
      console.log(res)
      this.videoFlag = false
      this.videoUploadPercent = 0
      this.showVideoPath = res.data.result
      this.formData.video = res.data.result
      this.videoHint = '重新选择'
    }
  }
}
</script>
<style lang="scss" scoped>
.block {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.red {
  color: red;
}
.gray {
  color: rgb(10, 184, 10);
}
.searchBox {
  display: flex;
  span {
    width: 50px;
    line-height: 40px;
    text-align: center;
  }
  .search {
    width: 30%;
  }
}
.searchMain {
  height: 80px;
}
:deep(.el-range-separator) {
  width: 30px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px !important;
  position: relative !important;
  overflow: hidden !important;
}
.avatar-uploader .el-upload:hover {
  border: 1px dashed #d9d9d9 !important;
  border-color: #409eff;
}
.avatar-uploader-icon {
  border: 1px dashed #d9d9d9 !important;
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 300px;
  height: 178px;
  display: block;
}
.videoBox {
  display: flex;
  position: relative;
  width: 300px;
  height: 178px;
}
.progress {
  width: 126px;
  height: 126px;
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  top: 0;
  margin: auto;
}
:deep(.el-dialog) {
  margin-top: 20px !important;
}
.video-avatar {
  margin-bottom: 20px;
}
.flexRow {
  display: flex;
  align-items: center;
}
</style>
